<template>
  <el-dialog
    :title="showTitle"
    :visible.sync="showdialogSubject"
    width="30%"
    @close="btnCancel"
  >
    <el-form
      :model="ruleForm"
      ref="ruleForm"
      label-width="100px"
      :rules="rules"
    >
      <el-form-item label="学科名称" prop="subjectName">
        <el-input
          v-model="ruleForm.subjectName"
          placeholder="请输入学科名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="是否显示">
        <el-switch
          v-model="ruleForm.isFrontDisplay"
          active-color="#13ce66"
          inactive-color="#ff4949"
        ></el-switch>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="btnCancel">取 消</el-button>
      <el-button type="primary" @click="btnOk">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  addSubjects,
  editSubjects,
  subjectsDetail,
} from "@/api/subjects/subjects";
export default {
  name: "dialogSubject",
  data() {
    return {
      showdialogSubject: false,
      ruleForm: {
        id: "",
        subjectName: "",
        isFrontDisplay: true,
      },
      rules: {
        subjectName: [
          { required: true, message: "学科名称不能为空", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "学科名称要求1-10个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  // props: {
  //   subjectId: {
  //     type: Number,
  //   },
  // },
  computed: {
    showTitle() {
      // id默认空串还是id.length
      return this.ruleForm.id ? "编辑学科" : "新增学科";
    },
  },
  methods: {
    // 获取表单数据，修改学科，数据回显,供父调用方法
    async subjectsDetail(id) {
      const { data } = await subjectsDetail(id);
      this.ruleForm = data;
    },

    // 取消按钮
    btnCancel() {
      this.$refs.ruleForm.resetFields();
      this.ruleForm = {
        id: "",
        subjectName: "",
        isFrontDisplay: true,
      };
      this.showdialogSubject = false;
    },
    //确定按钮
    async btnOk() {
      // 主动校验
      await this.$refs.ruleForm.validate();
      if (this.ruleForm.id) {
        //  编辑
        await editSubjects(this.ruleForm);
      } else {
        //  新增
        await addSubjects(this.ruleForm);
      }
      // 成功提示
      this.$message.success("操作成功");
      // 更新列表
      this.$emit("updateSubject");
      // 关闭弹层
      this.showdialogSubject = false;
    },
  },
};
</script>

<style scoped>
::v-deep .el-dialog__header {
  background-color: #43a4ff;
}
::v-deep .el-dialog__title {
  color: #fff;
}
 ::v-deep .el-icon-close:before{
  color: #fff;

}
</style>
